{{>partial_header}}
using System;
using System.ComponentModel;
using System.Globalization;
{{#useNewtonsoft}}
using Newtonsoft.Json;
{{/useNewtonsoft}}
{{^useNewtonsoft}}
using System.Text.Json;
{{/useNewtonsoft}}

namespace {{packageName}}.Converters
{
    /// <summary>
    /// Custom string to enum converter
    /// </summary>
    public class CustomEnumConverter<T> : TypeConverter
    {
        /// <summary>
        /// Determine if we can convert a type to an enum
        /// </summary>
        /// <param name="context"></param>
        /// <param name="sourceType"></param>
        /// <returns></returns>
        public override bool CanConvertFrom(ITypeDescriptorContext{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} context, Type sourceType)
        {
            return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
        }

        /// <summary>
        /// Convert from a type value to an enum
        /// </summary>
        /// <param name="context"></param>
        /// <param name="culture"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override object{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} ConvertFrom(ITypeDescriptorContext{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} context, CultureInfo{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} culture, object value)
        {
            var s = value as string;
            if (string.IsNullOrEmpty(s))
            {
                return null;
            }

            return {{#useNewtonsoft}}JsonConvert.DeserializeObject{{/useNewtonsoft}}{{^useNewtonsoft}}JsonSerializer.Deserialize{{/useNewtonsoft}}<T>(@"""" + value + @"""");
        }
    }
}
